<?php
/**
 * 描述
 * Created by Paco
 * Date: 2018/11/15 Time: 16:36
 */

namespace App\Repositories\Product;


use App\Models\Product\AttrName;
use App\Models\Product\AttrValue;
use App\Models\Product\TemplateAttr;
use App\Models\Product\TypeTemplate;
use App\Repositories\Repository;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Console\Tests\Tester\ApplicationTesterTest;

class AttribueRepository extends Repository
{

    public function getAttrNames()
    {
        $attr = AttrName::query()->with(['attrValue' => function ($query) {
            return $query->select('name', 'sort', 'attr_name_id', 'attr_value_id')->orderBy('sort', 'asc');
        }])->orderBy('attr_id', 'desc')
            ->paginate($this->page_size,
                ['name', 'sort', 'attr_id', 'is_spec', 'is_alias', 'is_search', 'group_name', 'input_type', 'is_required', 'group_number'],
                'page', $this->page);
        return $this->respondWith($attr);
    }

    public function getAttrName($attr_id)
    {
        $attr = AttrName::query()->with(['attrValue' => function ($query) {
            return $query->orderBy('sort', 'asc');
        }])->find($attr_id);

        return $this->respondWith($attr);
    }

    public function addAttrName($params)
    {
        //组装属性值
        DB::beginTransaction();
        try {
            $attr_name = AttrName::query()->create($params);
            if (isset($params['attr_values']) && count($params['attr_values'])) {
                if (!is_array($params['attr_values'])) {
                    $params['attr_values'] = explode(',', $params['attr_values']);
                }
                $date = date('Y-m-d H:i:S');
                foreach ($params['attr_values'] as $k => $attr_value) {
                    $params['attr_values'][$k]['attr_name_id'] = $attr_name->attr_id;
                    $params['attr_values'][$k]['created_at'] = $date;
                    $params['attr_values'][$k]['updated_at'] = $date;
                }
                AttrValue::query()->insert($params['attr_values']);
            }

            DB::commit();
            return $this->respondSuccess();
        } catch (\Exception $e) {
            DB::rollBack();
            //$this->throwRespondWithMessage($e->getMessage());
            $this->throwRespondError(10110);
        }
    }

    public function saveAttrName($params)
    {
        DB::beginTransaction();
        try {
            $attr_name = AttrName::query()->find($params['attr_id']);
            $attr_name->fill($params)->save();
            //前端将规则值分为更新与新添的数组

            //1、添加新属性值
            if (isset($params['attr_values']) && count($params['attr_values'])) {
                $date = date('Y-m-d H:i:S');
                foreach ($params['attr_values'] as $k => $attr_value) {
                    $params['attr_values'][$k]['attr_name_id'] = $attr_name->attr_id;
                    $params['attr_values'][$k]['created_at'] = $date;
                    $params['attr_values'][$k]['updated_at'] = $date;
                }
                AttrValue::query()->insert($params['attr_values']);
            }

            //2、更新属性值
            if (isset($params['save_attr_values']) && count($params['save_attr_values'])) {
                foreach ($params['save_attr_values'] as $k => $attr_value) {
                    if (!$this->saveAttrValue($attr_value)) {
                        DB::rollBack();
                        $this->throwRespondError(10108);
                    }
                }
            }
            $this->updateTemplate($params['attr_id']);
            DB::commit();
            return $this->respondSuccess();
        } catch (\Exception $e) {
            DB::rollBack();
            $this->throwRespondWithMessage($e->getMessage());
            $this->throwRespondError(10108);
        }
    }

    public function deleteAttribue($attr_id)
    {
        DB::beginTransaction();
        try {
            AttrName::query()->where('attr_id', $attr_id)->delete();
            AttrValue::query()->where('attr_name_id', $attr_id)->delete();
            DB::commit();
            return $this->respondSuccess();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->respondError(10107);
        }
    }

    public function deleteAttrValue($attr_value_id)
    {
        try {
            AttrValue::query()->where('attr_value_id', $attr_value_id)->delete();
            return $this->respondSuccess();
        } catch (\Exception $e) {
            return $this->respondError(10107);
        }
    }


    private function saveAttrValue($data)
    {
        $attr_value = AttrValue::query()->find($data['attr_value_id']);
        return $attr_value->fill($data)->save();
    }


    private function updateTemplate($attr_id)
    {
        $temps = TemplateAttr::query()->where('attr_id', $attr_id)->get();
        if (count($temps) > 0) {
            foreach ($temps as $temp) {
                $template = TypeTemplate::query()->where('template_id', $temp->template_id)->first();
                $attribues = json_decode($template->attribues);
                $tem_ids = [];
                foreach ($attribues as $attribue) {
                    $tem_ids[] = $attribue->attr_id;
                }
                $attribues = $this->getAttrs($tem_ids);
                $template->attribues = json_encode($attribues);
                $template->save();
            }
        }
    }

    private function getAttrs($attr_ids = [])
    {
        return AttrName::query()->with(['attrValue' => function ($query) {
            return $query->select('name', 'sort', 'attr_name_id', 'attr_value_id')->orderBy('sort', 'asc');
        }])->whereIn('attr_id', $attr_ids)
            ->select('name', 'sort', 'attr_id', 'is_spec', 'is_alias', 'is_search', 'group_name', 'input_type', 'is_required', 'group_number')
            ->orderBy('attr_id', 'desc')
            ->get();
    }
}